import React from 'react';
import { connect } from 'dva';

import { Modal, Table, Button, Form,DatePicker } from 'antd';

import moment from 'moment';


const FormItem = Form.Item;


@connect(({
  accountMoveLine,
  accountBalance
}) => ({
  accountMoveLine,
  accountBalance
}))
class List extends React.Component {
  state = {
    visible: false
  }

  treeview = [
      { title: '凭证号', dataIndex: 'move_id.name', },
      { title: '日期', dataIndex: 'date', },
      { title: '科目', dataIndex: 'account_id.name', },
      { title: '借方', dataIndex: 'debit', },
      { title: '贷方', dataIndex: 'credit', },
      { title: '摘要', dataIndex: 'move_id.ref', },
      { title: '状态', dataIndex: 'move_id.state', },
  ]

  async componentDidMount() {
    const { dispatch } = this.props;

    const domain = [
      ['move_id.state','=','posted'],
    ]

    await dispatch({
      type: 'accountMoveLine/search',
      payload: {
        domain,
        order: 'account_id, date'
      },

    });

  }

  showForm() {
    this.setState({visible: true})
  }

  handleCancel(){
    this.setState({visible: false})
  }

  handleOk(){
    const { dispatch, form } = this.props;

    form.validateFieldsAndScroll( async (err, values) => {
      if (!err) {

        const { date } = values;

        await dispatch({
          type: 'accountBalance/generate_balance',
          payload : {
            date: date.format('YYYY-MM-DD'),
          },
        });

        this.setState({visible: false})

      }
    });


  }


  render() {
    const { accountMoveLine: { recordsList } } = this.props;
    const { accountBalance: { isGenerated } } = this.props;


    const { form: { getFieldDecorator }  } = this.props;


    const { visible } = this.state;

    return (
      <div>

        <Button onClick={()=>this.showForm()}>计算余额</Button>

        {  isGenerated ? isGenerated>0 ? '计算完成 ok': '计算失败' : ''

        }

        <Modal title='计算余额'
          visible={visible}
          onOk={()=>this.handleOk()}
          onCancel={()=>this.handleCancel()}
        >

          <Form>

            <FormItem label="日期">
              {getFieldDecorator('date', {
                rules: [{ required: true }],
                initialValue:  moment()
               // initialValue: moment().format('YYYY-MM-DD')
               // initialValue: moment(record.date, 'YYYY-MM-DD'),
              })(<DatePicker />)}
            </FormItem>


          计算本期余额?


          </Form>


        </Modal>

        <Table columns={this.treeview} dataSource={recordsList} rowKey="id" />

      </div>
    );
  }
}

export default Form.create()(List);



